<template>
  <div class="flex items-center justify-center w-screen h-screen bg-gray-100 login">
    <div class="w-full p-4 bg-white rounded shadow-md login-wrapper sm:w-80">
      <div class="pb-1 mb-2 text-lg font-bold border-b border-gray-200 title">系统注册</div>
      <div class="p-2">
        <el-form size="small" :model="userInfo" :rules="rules" @submit="handleSubmit" ref="formEl">
          <el-form-item prop="username">
            <el-input placeholder="用户名" v-model="userInfo.username" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              placeholder="密码"
              type="password"
              v-model="userInfo.password"
              show-password
            />
          </el-form-item>
          <el-form-item prop="email">
            <el-input placeholder="邮箱" v-model="userInfo.email" />
          </el-form-item>
          <el-form-item>
            <el-button class="w-full" type="primary" native-type="submit">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { reqUserRegister } from '@/api/userApi';
  import { OK_CODE } from '@/app/keys';
  import { reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  const userInfo = reactive({
    username: '',
    password: '',
    email: '',
  });
  const rules = {
    username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
    email: [{ required: true, message: '邮箱不能为空', trigger: 'blue' }],
  };
  const formEl = ref<HTMLFormElement | null>();
  const router = useRouter();
  const handleSubmit = (e: Event) => {
    e.preventDefault();
    formEl.value!.validate().then(async (ok: boolean) => {
      if (!ok) return;
      try {
        let { code, data, msg } = await reqUserRegister(userInfo);
        if (code === OK_CODE) {
          ElMessage({
            type: 'success',
            message: msg,
          });
          router.push({ name: 'Login' });
          return;
        }
        ElMessage({
          type: 'error',
          message: msg,
        });
      } catch (e) {
        ElMessage.error(e as string);
      }
    });
  };
</script>

<style scoped></style>
